package com.lxt.filemanager.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxt.filemanager.common.FastDFSUtil;
import com.lxt.filemanager.entity.DFSAddress;
import com.lxt.filemanager.entity.TblFile;
import com.lxt.filemanager.mapper.TblFileMapper;
import com.lxt.filemanager.service.TblFileService;
import org.csource.common.MyException;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 文件服务实现
 */
@Service("tblFileService")
public class TblFileServiceImpl extends ServiceImpl<TblFileMapper, TblFile> implements TblFileService {
    /**
     * 上传文件
     * @param file
     * @param data
     * @return
     */
    @Override
    public boolean upLoad(TblFile file, byte[] data) throws IOException, MyException {
        DFSAddress upload = FastDFSUtil.upload(data,file.getExtName());
        file.setGroupId(upload.getGroup());
        file.setStoreAddress(upload.getAddress());
        boolean save = this.save(file);
        return save;
    }

    /**
     * 下载文件
     * @param id
     * @return
     * @throws IOException
     * @throws MyException
     */
    @Override
    public DFSAddress download(Integer id) throws IOException, MyException {
        TblFile tblFile = this.getById(id);
        DFSAddress dfsAddress = new DFSAddress();
        dfsAddress.setGroup(tblFile.getGroupId());
        dfsAddress.setAddress(tblFile.getStoreAddress());
        DFSAddress download = FastDFSUtil.download(dfsAddress);
        download.setFileName(tblFile.getFileName()+"."+tblFile.getExtName());
        return download;
    }

    /**
     * 删除文件
     * @param tblFile
     * @return
     * @throws IOException
     * @throws MyException
     */
    @Override
    public boolean delete(Integer id) throws IOException, MyException {
        TblFile tblFile = this.getById(id);
        DFSAddress dfsAddress = new DFSAddress();
        dfsAddress.setGroup(tblFile.getGroupId());
        dfsAddress.setAddress(tblFile.getStoreAddress());
        FastDFSUtil.delete(dfsAddress);
        this.removeById(tblFile);
        return true;
    }

}
